<script setup>
import {getCurrentInstance, ref, watch} from "vue";
import {cloneDeep} from "lodash";
import {checkPwdStrong} from "@/utils/utils";
import {md5} from "js-md5";
import {resetPwd} from "@/api/system/user";

const {proxy} = getCurrentInstance();
const emit = defineEmits(['success']);
const modalRef = ref();
const formRef = ref();
const formData = ref({
  userId: undefined,
  password: '',
})
const msgText = ref()
const pwdPercentage = ref(0)
const pwdColor = ref("#FF5340")
const pwdFormatF = ref('弱')

const open = async (userId) => {
  resetForm();
  formData.value = {
    userId: userId,
    password: ''
  }
  modalRef.value.handleOpen()
}

const handleSubmit = async () => {
  const result = await formRef.value.validate();
  if(result){
    return false;
  }
  let data = cloneDeep(formData.value);
  data.password = md5(data.password)
  await resetPwd(data);
  proxy.$modal.okNotify('密码重置成功');
  resetForm();
  modalRef.value.handleClose();
  emit('success')
}

const resetForm = () => {
  formRef.value?.resetFields();
  formData.value = {
    userId: undefined,
    password: '',
  }
}

watch(() => formData.value.password, (newVal) => {
  msgText.value = checkPwdStrong(newVal);
  if (msgText.value > 1 || msgText.value === 1) {
    pwdPercentage.value = 30;
    pwdColor.value = "#FF5340";
    pwdFormatF.value = '弱'
  }
  if (msgText.value > 2 || msgText.value === 2) {
    pwdPercentage.value = 60;
    pwdColor.value = "#FFB640"
    pwdFormatF.value = '中'
  }
  if (msgText.value === 4) {
    pwdPercentage.value = 100;
    pwdColor.value = "#25DC1B"
    pwdFormatF.value = '强'
  }
}, {
  immediate: true
})

defineExpose({open})
</script>

<template>
  <dialog-form ref="modalRef" modalTitle="重置密码" modalWidth="500px"
               @submit="handleSubmit">
    <a-form ref="formRef" :model="formData" label-width="80px">
      <a-form-item label="登录密码" field="password" style="margin-bottom: unset" :required="true"
                    :rules="[
              {
                required: true,
                message: '请输入密码',
                trigger: 'blur'
              }
            ]">
        <a-input-password v-model="formData.password"
                  placeholder="请输入密码"/>
      </a-form-item>
      <div style="margin: 18px 0 18px 100px">
        <a-progress :percent="pwdPercentage" :stroke-width="14" :color="pwdColor">
          <template v-slot:text="scope">
            {{ pwdFormatF }}
          </template>
        </a-progress>
      </div>
    </a-form>
  </dialog-form>
</template>

<style scoped lang="scss">

</style>
